package com.analyse.stock.strategy.indicator;

import org.ta4j.core.Indicator;
import org.ta4j.core.indicators.AbstractIndicator;
import org.ta4j.core.num.Num;

/**
 * 自定义指标
 * 资金流向异动指标
 */
public class FundFlowAnomalyIndicator extends AbstractIndicator<Num> {
    private final Indicator<Num> netCapitalFlowIndicator; // 主力净流入资金数据
    private final int period; // 异动判断的时间窗口
    private final double threshold; // 异动阈值（如 ±50%）

    // 构造函数
    public FundFlowAnomalyIndicator(Indicator<Num> netCapitalFlowIndicator, int period, double threshold) {
        super(netCapitalFlowIndicator.getBarSeries());
        this.netCapitalFlowIndicator = netCapitalFlowIndicator;
        this.period = period;
        this.threshold = threshold;
    }

    @Override
    public Num getValue(int index) {
        if (index < period) {
            // 数据不足，返回 0
            return numOf(0);
        }
        // 当前主力净流入资金
        Num currentFlow = netCapitalFlowIndicator.getValue(index);

        // 计算过去 N 天主力净流入资金的平均值
        Num totalFlow = numOf(0);
        for (int i = index - period + 1; i <= index; i++) {
            totalFlow = totalFlow.plus(netCapitalFlowIndicator.getValue(i));
        }
        Num averageFlow = totalFlow.dividedBy(numOf(period));

        // 计算当前值偏离平均值的百分比
        Num deviation = currentFlow.minus(averageFlow).dividedBy(averageFlow).multipliedBy(numOf(100));

        // 判断是否超过阈值
        return deviation.abs().isGreaterThan(numOf(threshold)) ? deviation : numOf(0);
    }
}
